package demo2;

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 判断岛屿数量
     * @param grid char字符型二维数组 
     * @return int整型
     */
    int n,m;
    int[] xx = {1,-1,0,0};
    int[] yy = {0,0,1,-1};
    boolean[][] st;
    public int solve (char[][] grid) {
        n = grid.length;
        m = grid[0].length;
        st = new boolean[n][m];
        int count = 0;
        for(int i = 0; i<n; i++) {
            for(int j = 0; j<m; j++) {
                if(grid[i][j] == '1' && !st[i][j]) {
                    count++;
                    st[i][j] = true;
                    dfs(grid, i, j);
                }
            }
        }

        return count;
    }
    public void dfs(char[][] grid, int x, int y) {
        for(int i = 0; i<4; i++) {
            int dx = x + xx[i];
            int dy = y + yy[i];
            if(dx >= 0 && dx < n && dy >= 0 && dy < m && grid[dx][dy] == '1' && !st[dx][dy]) {
                st[dx][dy] = true;
                dfs(grid, dx, dy);
            }
        }
    }
}